package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.json.Json;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Component
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Value("${file.oss.web-site}")
    private String webSite;
    @Autowired
    WmNewsService wmNewsService;
    @Autowired
    private AdminFeign adminFeign;
    @Autowired
    GreenScan greenScan;

    @Override
    public void autoScanWmNews(Integer id) {
        //1.校验id不能为空
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "id为空,审核失败");
        }
        //2.根据id查询文章数据
        WmNews wmNews = wmNewsService.getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "对应的文章信息不存在");
        }
        //3.判断文章审核是否为1(待审核)
        Short status = wmNews.getStatus();
        if (!(status.shortValue() == WmNews.Status.SUBMIT.getCode())){

            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章状态不为待审核,无需审核");
        }
        //4.提取文章中所有的文本内容 和图片内容路径
        Map<String, Object> textAndImages = handleTextAndImages(wmNews);
        String content = (String) textAndImages.get("content");
        List<String> images = (List<String>) textAndImages.get("images");
        //5 .进行自管理敏感词校验
        boolean handleASensitive = handleSenSitive(content, wmNews);
        if (!handleASensitive) {
            log.info("文章中包含敏感词,敏感词审核未通过========================================");
            return;
        }
        //6.进行阿里云内容安全 文本检测
        boolean textScan = handleTextScan(content, wmNews);
        if (!textScan) {
            log.info("文章中 包含违规词汇,阿里云文本审核未通过==========================");
            return;
        }
        // 7.进行阿里云内容安全 文本检测
        //pass(通过下一步)  review(3.人工审核)   block(2失败 )
        if (!CollectionUtils.isEmpty(images)) {
            boolean imageScan = handleImageScan(images, wmNews);
            if (!imageScan) {
                log.info("文章中 包含违规图片,阿里云图片审核未通过==========================");
                return;
            }
        }
        //8.如果全部检测通过,将状态修改为8(通过)
        updateWmNews(wmNews, WmNews.Status.SUCCESS.getCode(), "审核通过");
        //9.发送延时消息进行文章发布上架操作
        //1.获取发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        //2.获取当前时间
        long nowTime = System.currentTimeMillis();
        //3.距离发布时间=发布时间-当前时间
        long remainTime = publishTime - nowTime;
        //4.发送消息,并设置消息头 x-delay: 距离发布时间
        rabbitTemplate.convertAndSend(
                PublishArticleConstants.DELAY_DIRECT_EXCHANGE,
                PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,
                wmNews.getId(),
                new MessagePostProcessor() {
                    /**
                     * 消息后置处理器用于改变消息属性
                     * @param message
                     * @return
                     * @throws AmqpException
                     */
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        message.getMessageProperties()
                                .setHeader("x-delay", remainTime <= 0 ? 0 : remainTime);
                        return message;
                    }
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 调用阿里云图片审核
     *
     * @param images 待审核图片内容
     * @param wmNews 图片对象
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag = false;
        try {
            ScanResult scanResult = greenScan.imageUrlScan(images);
            String suggestion = scanResult.getSuggestion();
            switch (suggestion) {
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "图片中包含违规词汇,审核未通过" + scanResult.getLabel());
                    break;
                case "review":
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文章图片中有不确定因素，需要进一步人工审核" + scanResult.getLabel());
                    break;
                case "pass":
                    flag = true;
                    break;
                default:
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "阿里云审核出现异常,转为人工审核");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "阿里云审核出现异常,转为人工审核");
        }
        return flag;
    }

    /**
     * 调用阿里云文本审核
     *
     * @param content 待审核文本内容
     * @param wmNews  文章对象
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = false;
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            String suggestion = scanResult.getSuggestion();
            //pass(通过下一步)  review(3.人工审核)   block(2失败 )
            switch (suggestion) {
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文本中包含违规词汇,审核未通过" + scanResult.getLabel());
                    break;
                case "review":
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文章图片中有不确定因素，需要进一步人工审核" + scanResult.getLabel());
                    break;
                case "pass":
                    flag = true;
                    break;
                default:
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "阿里云审核出现异常,转为人工审核");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            //转为人工审核
            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "阿里云审核出现异常,转为人工审核");
        }
        return flag;
    }

    /**
     * 敏感词审核
     *
     * @param content 文本内容
     * @param wmNews  文章对象
     * @return
     */
    private boolean handleSenSitive(String content, WmNews wmNews) {
        //1.基于feign远程查询敏感词列表
        ResponseResult<List<String>> sensitives = adminFeign.sensitives();
        //如果不为ture就报异常
        if (!sensitives.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        //得到敏感词列表
        List<String> data = sensitives.getData();
        //2.基于DFA算法,封装数据模型
        SensitiveWordUtil.initMap(data);
        //3.基于DFA算法,检测内容是否包敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        //4.如果包含敏感词将文章状态修改为2(审核失败)
        if (!CollectionUtils.isEmpty(map)) {
            updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "内容包含敏感词" + map);
            return false;
        }
        return true;
    }

    private void updateWmNews(WmNews wmNews, Short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsService.updateById(wmNews);
    }

    /**
     * 抽取文章中 所有的文本内容 和图片内容
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        String contentJson = wmNews.getContent(); // [{},{},{}]
        if (StringUtils.isBlank(contentJson)) {
            log.error("自动审核文章失败    文章内容为空");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章内容为空");
        }
        List<Map> contentMaps = JSONArray.parseArray(contentJson, Map.class);
        // 1. 抽取文章中所有文本     家乡很美   _hmtt_   国家伟大
        String content = contentMaps.stream()
                .filter(map -> "text".equals(map.get("type")))
                .map(map -> (String) map.get("value"))
                .collect(Collectors.joining("_hmtt_"));
        content = content + "_hmtt_" + wmNews.getTitle();

        // 2. 抽取文章中所有图片   content :  全路径       images :  文件名称  + 访问前缀
        List<String> imageList = contentMaps.stream()
                .filter(map -> "image".equals(map.get("type")))
                .map(map -> (String) map.get("value"))
                .collect(Collectors.toList());
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            // 按照 逗号 切割封面字符串  得到数组   基于数组得到stream   将每一条数据都拼接一个前缀 收集成集合
            List<String> urls = Arrays.stream(wmNews.getImages().split(","))
                    .map(url -> webSite + url)
                    .collect(Collectors.toList());
            imageList.addAll(urls);
        }
        // 3. 去重
        imageList = imageList.stream().distinct().collect(Collectors.toList());

        Map result = new HashMap();
        result.put("content", content);
        result.put("images", imageList);
        return result;
    }
}
